package org.example.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.alibaba.fastjson.JSON;
import org.example.easyexcel.bean.MergeData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MergeListener extends AnalysisEventListener<MergeData> {

    private static final Logger logger = LoggerFactory.getLogger(MergeListener.class);
    private List<MergeData> list = new ArrayList<MergeData>();

    private Map<Integer, String> headMap = null;
    private boolean isReadHead = false;
    private int rownum=1;

    public List<MergeData> getList() {
        return list;
    }

    public void setList(List<MergeData> list) {
        this.list = list;
    }

    public Map<Integer, String> getHeadMap() {
        return headMap;
    }

    public void setHeadMap(Map<Integer, String> headMap) {
        this.headMap = headMap;
    }

    public boolean isReadHead() {
        return isReadHead;
    }

    public void setReadHead(boolean readHead) {
        isReadHead = readHead;
    }

    /**
     * 读取一行就调用一次(默认自动忽略第一行)
     * @param mergeData
     * @param analysisContext
     */
    public void invoke(MergeData mergeData, AnalysisContext analysisContext) {
        Integer rowIndex = analysisContext.readRowHolder().getRowIndex();
        logger.info("第{}行:{}",rowIndex,JSON.toJSONString(mergeData));
        list.add(mergeData);
    }


    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        ReadSheetHolder readSheetHolder = analysisContext.readSheetHolder();
        logger.info("{}一共{}行",readSheetHolder.getSheetName(),readSheetHolder.getApproximateTotalRowNumber());
        //rownum+=readSheetHolder.getApproximateTotalRowNumber();
        logger.info("list:"+list.size());
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
        logger.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
    }
    @Override
    public boolean hasNext(AnalysisContext context) {
        return !isReadHead;
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        logger.info("读取到了一条额外信息:{}", JSON.toJSONString(extra));
        switch (extra.getType()) {
            case MERGE:
                logger.info(
                        "额外信息是合并,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{}",
                        extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
                        extra.getLastColumnIndex());
                break;
        }
    }
}
